package app.fugema.shop.main.evaluate.view;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RatingBar;

import com.base.common.app.LoginUtils;
import com.base.common.model.bean.ADInfo;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.Base64Utils;
import com.base.common.utils.DialogUtils;
import com.base.common.utils.JavaMethod;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.ada.BaseRVAdapter;
import com.base.common.view.adapter.ada.ImageAddRecyAdapter;
import com.base.common.view.adapter.ada.SingleRecyclerAdapter;
import com.base.common.view.adapter.connector.BaseItemMultiType;
import com.base.common.view.adapter.connector.BaseViewHolder;
import com.base.common.view.base.BaseTitleActivity;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.EvaluateAddAcBinding;
import app.fugema.shop.databinding.ItemEvaluateProductViewBinding;
import app.fugema.shop.http.HttpService;
import app.fugema.shop.main.evaluate.model.GoodsComment;
import app.fugema.shop.main.evaluate.model.ProductPostComment;
import app.fugema.shop.main.evaluate.vm.EvaluateVM;

import java.util.ArrayList;
import java.util.List;

import app.fugema.shop.main.evaluate.model.CommentProductResult;
import app.fugema.shop.main.order.view.OrderAfterSaleCreateActivity;
import app.fugema.shop.main.setting.model.UploadPicResult;
import app.fugema.shop.util.SimpleTextWatcher;
import io.reactivex.Observable;

public class EvaluateAddActivity extends BaseTitleActivity<EvaluateAddAcBinding, EvaluateVM> {


    public static void start(Context context,  Long orderId)
    {
        if (orderId == null) return;
        Intent starter = new Intent(context, EvaluateAddActivity.class);
        starter.putExtra("orderId", orderId);
        context.startActivity(starter);
    }

    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.evaluate_add_ac);
    }

    private Long orderID;
    private String userKey;

    private SingleRecyclerAdapter<ProductPostComment,ItemEvaluateProductViewBinding> productAdapter;

    private List<ProductPostComment>  postCommentList;

    //private ImageAddRecyAdapter imageAddRecyAdapter;

    @Override
    protected void initView()
    {
        super.initView();
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("评价",R.color.white);
        /*
        binding.rbRating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                if (rating >= 4.0f) {
                    binding.tvLikeText.setText("非常喜欢");
                } else if (rating >= 3) {
                    binding.tvLikeText.setText("感觉一般");
                } else {
                    binding.tvLikeText.setText("非常厌恶");
                }
            }
        });
        */

        productAdapter = new SingleRecyclerAdapter<ProductPostComment, ItemEvaluateProductViewBinding>(this)
        {
            @Override
            public int getLayoutId()
            {
                return R.layout.item_evaluate_product_view;
            }

            @Override
            public void onCreateViewHolder(ItemEvaluateProductViewBinding binding, BaseViewHolder viewHolder)
            {
                super.onCreateViewHolder(binding, viewHolder);
                final LifecycleOwner owner = getLifecycleOwner();
                ImageAddRecyAdapter tempImgAddAdapter = new ImageAddRecyAdapter( EvaluateAddActivity.this ){
                    @Override
                    public Observable<Object> getObservable(String path)
                    {
                        viewModel.upLoadPIc(Base64Utils.imgFileToBase64Str(path))
                            .observe(owner, new BaseViewObserver<LiveDataWrapper<UploadPicResult>>()
                            {
                                @Override
                                protected void onSuccess(LiveDataWrapper<UploadPicResult> data)
                                {
                                    if( data.data.isSuccess() )
                                    {
                                        LogUtil.e( data.data.getRomoteImage() );
                                        LogUtil.e("ImageAddRecyAdapter","发送网络图片Url");
                                        LiveEventBus.get("netImg",String.class).post( data.data.getSrc() );
                                    }
                                }
                            });

                        return viewModel.getUpLoadFilesObservable(path, HttpService.getUpLoadFilesService());
                    }
                } ;
                tempImgAddAdapter.setMaxCount(3);
                tempImgAddAdapter.setVideoCount(0);
                tempImgAddAdapter.setSelectedGif(false);
                tempImgAddAdapter.setAutoUpload(true);

                binding.rvRecyclerViewImages.setAdapter(tempImgAddAdapter);

            }

            @Override
            public void onBindViewHolder(ItemEvaluateProductViewBinding binding, int position, ProductPostComment bean)
            {
                super.onBindViewHolder(binding, position, bean);

                binding.ratingbarGoods.setOnRatingChangeListener( (bar, RatingCount) -> {
                    //设置 商品评分
                    bean.setMark( String.valueOf( (int) RatingCount  ) );
                } );
                // 初始化时 5 分
                bean.setMark("5");
                // 单个商品的 评论
                binding.etProductComment.addTextChangedListener(new SimpleTextWatcher() {
                    @Override
                    public void afterTextChanged(String content)
                    {
                        bean.setContent( content );
                    }
                });

                if (binding.rvRecyclerViewImages.getAdapter() instanceof ImageAddRecyAdapter)
                {
                    ImageAddRecyAdapter tempImgAddAdapter = (ImageAddRecyAdapter) binding.rvRecyclerViewImages.getAdapter();
                    tempImgAddAdapter.addFoot();
                }

                if( UIUtils.isEmpty( bean.getImages() ) )
                {
                    bean.setImages(new ArrayList<String>());
                }
                LiveEventBus.get("netImg",String.class)
                            .observe(getLifecycleOwner(),netImgUrl -> {
                                LogUtil.e("Adapter","保存网络图片");
                                bean.getImages().add( netImgUrl );
                            });
            }

            @Override
            public void onItemClick(View view, BaseRVAdapter adapter, int onclickType, int position, ProductPostComment bean)
            {
                super.onItemClick(view, adapter, onclickType, position, bean);
            }
        };

        binding.rvRecyclerView.setAdapter( productAdapter );
        /*
        imageAddRecyAdapter = new ImageAddRecyAdapter(this) {
            @Override
            public Observable<Object> getObservable(String path)
            {

                return viewModel.getUpLoadFilesObservable(path, HttpService.getUpLoadFilesService());
            }
        };
        imageAddRecyAdapter.setMaxCount(3);
        imageAddRecyAdapter.setVideoCount(0);
        imageAddRecyAdapter.setSelectedGif(false);
        imageAddRecyAdapter.setAutoUpload(true);
        binding.rvRecyclerViewImages.setAdapter(imageAddRecyAdapter);
        imageAddRecyAdapter.addFoot();
        */
        binding.rtvOK.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                save();
            }
        });
    }

    @Override
    protected void initData(Intent intent)
    {
        super.initData(intent);
        userKey = LoginUtils.getToken();
        //JacksonUtils.getJsonBean(, String.class)
        orderID = intent.getLongExtra("orderId",0)  ;
        if( orderID != 0 )
        {
            queryProductInfo(orderID);
        }

    }

    private void queryProductInfo(Long mOrderId)
    {
        viewModel.getCommentProductByOder(mOrderId,userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<CommentProductResult>>()
                 {
                     @Override
                     protected void onSuccess(LiveDataWrapper<CommentProductResult> data)
                     {
                          if( data.data.isSuccess() )
                          {
                               if( UIUtils.isNotEmpty( data.data.getProduct() ) )
                               {
                                   postCommentList = ProductPostComment.getProductListByResult( data.data );
                                   productAdapter.setDataList( postCommentList );
                               }
                          }
                     }

                     @Override
                     public boolean isEmptyData(LiveDataWrapper<CommentProductResult> data)
                     {
                         return UIUtils.isEmpty( data.data.getProduct() );
                     }
                 });

    }


    private void save()
    {
        /*
        String ss = binding.etEdit.getText().toString();
        ss = ss.replaceAll(" ", "");
        if (UIUtils.isEmpty(ss)) {
            UIUtils.showToastSafesClose("内容不能为空");
            return;
        }
        */
        /*
        if (imageAddRecyAdapter != null && imageAddRecyAdapter.getChildCount() > 0)
        {

            //0  全部成功   1正在上传  2 上传完毕但是有图片上传失败
            int err = imageAddRecyAdapter.checkedUpload();
            if (err == 0) {
                List<ADInfo> list1 = imageAddRecyAdapter.getDataList(BaseItemMultiType.TYPE_CHILD, BaseItemMultiType.TYPE_CHILD_ONE);
                String pic = "";
                if (!UIUtils.isEmpty(list1)) {
                    pic = list1.get(0).getImageUrl();
                    for (int i = 1; i < list1.size(); i++) {
                        pic += "," + list1.get(i).getImageUrl();
                    }
                }
                save(ss, pic);
            } else {

                if (err == 1) {
                    Dialog progressDialog = DialogUtils.progressDialog(getActivity());
                    ProgressBar pbProgress = progressDialog.getWindow().findViewById(R.id.pbProgress);
                    ProgressBar pbProgressSum = progressDialog.getWindow().findViewById(R.id.pbProgressSum);

                    UIUtils.showToastSafes("正在上传图片，请稍后");

                    imageAddRecyAdapter.setUploadImageCallBack(new ImageAddRecyAdapter.UploadImageCallBack() {
                        @Override
                        public void onProgressSum(String percentSum) {
                            LogUtil.d(percentSum + "%  percentSum");
                            if (pbProgressSum != null) {
                                pbProgressSum.setProgress(JavaMethod.getInt(percentSum));
                            }
                        }

                        @Override
                        public void onProgress(String percent) {
                            LogUtil.d(percent + "%    percent");
                            if (pbProgress != null) {
                                pbProgress.setProgress(JavaMethod.getInt(percent));
                            }
                        }

                        @Override
                        public void onComplete(boolean success) {
                            dismissLoad();
                            if (success) {
                                save();
                            } else {
//                            LogUtil.d("上传完毕,但有图片上传失败");
                                DialogUtils.showSimpleDialog(getActivity(), false, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        save();
                                        dialog.dismiss();
                                    }
                                }, "上传完毕,但有图片上传失败\n是否继续提交？");

                            }
                        }
                    });

                } else {

                    DialogUtils.showSimpleDialog(getActivity(), false, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            save();
                            dialog.dismiss();
                        }
                    }, "上传完毕,但有图片上传失败\n是否继续提交？");

                }

            }
        } else {
            save(ss, null);
        }
        */
        List<GoodsComment> comments = new ArrayList<>();
        for(ProductPostComment productPostComment : (ArrayList<ProductPostComment>)productAdapter.getDatas())
        {
            GoodsComment tempComment = new GoodsComment();
            tempComment.setContent( productPostComment.getContent() );
            tempComment.setMark( productPostComment.getMark() );
            tempComment.setOrderItemId( productPostComment.getOrderItemId() );
            tempComment.setImages(productPostComment.getImages());
            comments.add(tempComment );
        }
        postSubmit(comments);

    }

    private void postSubmit(List<GoodsComment> comments)
    {
        //(int) binding.rbRating.getRating()


        viewModel.postAddEvaluate(orderID,comments,userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(this)
                 {
                    @Override
                    protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                    {
                        UIUtils.showToastSafes("评价成功");
                        LiveEventBus.get(AppConstants.EventKey.COMMENT_COMPLETE, String.class).post(String.valueOf(orderID));
                        finish();
                    }
                });

    }

}
